﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Text;
using System.EnterpriseServices;
using System.Configuration;
using Models;
using Common;
using Langben.DAL;
using Langben.BLL;
using Langben.App.Models;

namespace Langben.App.Controllers
{
    /// <summary>
    /// Cinerarium
    /// </summary>
    public class CinerariumController : BaseController
    {

        SysEntities db=new SysEntities();
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        [SupportFilter]
        public ActionResult Index()
        {
        
            return View();
        }
        public ActionResult Choose()
        {
        
            return View();
        }

        
         /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        public ActionResult IndexSef()
        {

            return View();
        }
        /// <summary>
        /// 异步加载数据
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="rows">每页显示的行数</param>
        /// <param name="order">排序字段</param>
        /// <param name="sort">升序asc（默认）还是降序desc</param>
        /// <param name="search">查询条件</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetData(string id, int page, int rows, string order, string sort, string search)
        {

            int total = 0;
            List<Cinerarium> queryData = m_BLL.GetByParam(id, page, rows, order, sort, search, ref total);
            return Json(new datagrid
            {
                total = total,
                rows = queryData.Select(s => new
                {
                    RowGuid = s.RowGuid
					,CreateTime = s.CreateTime
					,CreatePerson = s.CreatePerson
					,Price = s.Price
					,Pai = s.Pai
					,Hao = s.Hao
					,AreaGuid = s.AreaGuid
					,AreaName = s.AreaName
					
                }

                    )
            });
        }
        /// <summary>
        ///  导出Excle /*在6.0版本中 新增*/
        /// </summary>
        /// <param name="param">Flexigrid传过到后台的参数</param>
        /// <returns></returns>      
        [HttpPost]
        public ActionResult Export(string id, string title, string field, string sortName, string sortOrder, string search)
        {
            string[] titles = title.Split(',');//如果确定显示的名称，可以直接定义
            string[] fields = field.Split(',');
            List<Cinerarium> queryData = m_BLL.GetByParam(id, sortOrder, sortName, search);
             
            return Content(WriteExcle(titles, fields, queryData.ToArray()));  
        }
        /// <summary>
        /// 查看详细
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [SupportFilter]  
        public ActionResult Details(string id)
        {
            Cinerarium item = m_BLL.GetById(id);
            return View(item);

        }
 
        /// <summary>
        /// 首次创建
        /// </summary>
        /// <returns></returns>
        [SupportFilter]
        public ActionResult Create(string id)
        { 
            
            return View();
        }
        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [SupportFilter]
        public ActionResult Create(Cinerarium entity)
        {           
            if (entity != null && ModelState.IsValid)
            {
                string currentPerson = GetCurrentPerson();
                entity.CreateTime = DateTime.Now;
                entity.CreatePerson = currentPerson;
              
                entity.RowGuid = Result.GetNewId();   
                string returnValue = string.Empty;
                if (m_BLL.Create(ref validationErrors, entity))
                {
                    LogClassModels.WriteServiceLog(Suggestion.InsertSucceed  + "，Cinerarium的信息的Id为" + entity.RowGuid,"Cinerarium"
                        );//写入日志 
                    return Json(Suggestion.InsertSucceed);
                }
                else
                { 
                    if (validationErrors != null && validationErrors.Count > 0)
                    {
                        validationErrors.All(a =>
                        {
                            returnValue += a.ErrorMessage;
                            return true;
                        });
                    }
                    LogClassModels.WriteServiceLog(Suggestion.InsertFail + "，Cinerarium的信息，" + returnValue,"Cinerarium"
                        );//写入日志                      
                    return Json(Suggestion.InsertFail  + returnValue); //提示插入失败
                }
            }

            return Json(Suggestion.InsertFail + "，请核对输入的数据的格式"); //提示输入的数据的格式不对 
        }
        /// <summary>
        /// 首次编辑
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns> 
        [SupportFilter] 
        public ActionResult Edit(string id)
        {
            Cinerarium item = m_BLL.GetById(id);
            return View(item);
        }
        /// <summary>
        /// 提交编辑信息
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="collection">客户端传回的集合</param>
        /// <returns></returns>
        [HttpPost]
        [SupportFilter]
        public ActionResult Edit(string id, Cinerarium entity)
        {
            if (entity != null && ModelState.IsValid)
            {   //数据校验
            
                string currentPerson = GetCurrentPerson();                 
                //entity.UpdateTime = DateTime.Now;
                //entity.UpdatePerson = currentPerson;
                           
                string returnValue = string.Empty;   
                if (m_BLL.Edit(ref validationErrors, entity))
                {
                    LogClassModels.WriteServiceLog(Suggestion.UpdateSucceed + "，Cinerarium信息的Id为" + id,"Cinerarium"
                        );//写入日志                           
                    return Json(Suggestion.UpdateSucceed); //提示更新成功 
                }
                else
                { 
                    if (validationErrors != null && validationErrors.Count > 0)
                    {
                        validationErrors.All(a =>
                        {
                            returnValue += a.ErrorMessage;
                            return true;
                        });
                    }
                    LogClassModels.WriteServiceLog(Suggestion.UpdateFail + "，Cinerarium信息的Id为" + id + "," + returnValue, "Cinerarium"
                        );//写入日志                           
                    return Json(Suggestion.UpdateFail  + returnValue); //提示更新失败
                }
            }
            return Json(Suggestion.UpdateFail + "请核对输入的数据的格式"); //提示输入的数据的格式不对               
          
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>   
        [HttpPost]
        public ActionResult Delete(FormCollection collection)
        {
            string returnValue = string.Empty;
            string[] deleteId = collection["query"].GetString().Split(',');
            if (deleteId != null && deleteId.Length > 0)
            { 
                if (m_BLL.DeleteCollection(ref validationErrors, deleteId))
                {
                    LogClassModels.WriteServiceLog(Suggestion.DeleteSucceed + "，信息的Id为" + string.Join(",", deleteId), "消息"
                        );//删除成功，写入日志
                    return Json("OK");
                }
                else
                {
                    if (validationErrors != null && validationErrors.Count > 0)
                    {
                        validationErrors.All(a =>
                        {
                            returnValue += a.ErrorMessage;
                            return true;
                        });
                    }
                    LogClassModels.WriteServiceLog(Suggestion.DeleteFail + "，信息的Id为" + string.Join(",", deleteId)+ "," + returnValue, "消息"
                        );//删除失败，写入日志
                }
            }
            return Json(returnValue);
        }
     
        IBLL.ICinerariumBLL m_BLL;

        ValidationErrors validationErrors = new ValidationErrors();

        public CinerariumController()
            : this(new CinerariumBLL()) { }

        public CinerariumController(CinerariumBLL bll)
        {
            m_BLL = bll;
        }
        
        public JsonResult CreateCinerarium(string areaguid, string painame, int paisort, int startno, int endno, decimal price)
        {
            string currentPerson = GetCurrentPerson();
            string returnValue = string.Empty;
            List<Cinerarium> Cinerariumlist=new List<Cinerarium>();

            for (int i = startno; i <=endno; i++)
            {
                Cinerarium cinerarium = new Cinerarium();
                cinerarium.AreaGuid = areaguid;
                cinerarium.RowGuid = Convert.ToString(Guid.NewGuid());
                cinerarium.PaiName = painame;//排名称
                cinerarium.Pai = paisort;//排排序
                cinerarium.Hao = i;//一排的第几号
                cinerarium.CreatePerson = currentPerson;
                cinerarium.CreateTime = DateTime.Now;
                cinerarium.Price = price;
                Cinerariumlist.Add(cinerarium);
            }
            CinerariumBLL bll=new CinerariumBLL();
            if (bll.CreateCollection(ref validationErrors, Cinerariumlist.AsQueryable()))
            {
                return Json("创建成功");
            }
            else
            {
                if (validationErrors != null && validationErrors.Count > 0)
                {
                    validationErrors.All(a =>
                    {
                        returnValue += a.ErrorMessage;
                        return true;
                    });
                }
            }



            return Json(returnValue);
        }
          

        

            /// <summary>
        /// 获取寄存位布局div
        /// </summary>
        /// <param name="areaguid"></param>
        /// <returns></returns>
        public JsonResult GetCinerariumString(string areaguid)
        {
            string currentPerson = GetCurrentPerson();
            string returnValue = string.Empty;
            StringBuilder sb = new StringBuilder();

            CinerariumArea area = new CinerariumArea();
            try
            {
                area = new SysEntities().CinerariumArea.SingleOrDefault(s => s.RowGuid == areaguid);
            }
            catch (Exception)
            {
            
            }

            if (area != null)
            {
                string pai = area.Pai;
                string hao = area.Hao;
                IQueryable<int?> painolist;
                //从上往下
                if (string.IsNullOrEmpty(pai) || pai=="从上到下")
                {
                     painolist =
                    db.Cinerarium.Where(s => s.AreaGuid == areaguid)
                        .GroupBy(l => l.Pai)
                        .OrderBy(p => p.Key)
                        .Select(g => g.Key);
                }
                else
                {
                    painolist =
                    db.Cinerarium.Where(s => s.AreaGuid == areaguid)
                        .GroupBy(l => l.Pai)
                        .OrderByDescending(p => p.Key)
                        .Select(g => g.Key);
                }
                
                foreach (var paino in painolist)
                {
                    //根据paino获取painame
                    string paineme = string.Empty;
                    Cinerarium painameCinerarium = new Cinerarium();
                    try
                    {
                        painameCinerarium = db.Cinerarium.First(s => s.Pai == paino && s.AreaGuid==areaguid);
                    }
                    catch (Exception)
                    {
                    }
                    if (painameCinerarium != null)
                    {
                        paineme = painameCinerarium.PaiName;
                    }

                    SetStart(sb);
                    CinerariumBLL CinerariumBll = new CinerariumBLL();
                    List<Cinerarium> Cinerariumlist = new List<Cinerarium>();
                    //从左到右
                    if (hao == "从左到右" || string.IsNullOrEmpty(hao))
                    {
                        Cinerariumlist = CinerariumBll.GetAll()
                            .Where(s => s.AreaGuid == areaguid && s.Pai == paino)
                            .OrderBy(p => p.Hao)
                            .ToList();
                    }
                    else
                    {
                        Cinerariumlist = CinerariumBll.GetAll()
                            .Where(s => s.AreaGuid == areaguid && s.Pai == paino)
                            .OrderByDescending(p => p.Hao)
                            .ToList();
                    }
                    
                    SetSelectAllPai(sb, paino, paineme);

                    foreach (var cinerarium in Cinerariumlist)
                    {
                        SetCinerariumEntity(sb, cinerarium);
                    }

                    SetEnd(sb);
                }
            }
            returnValue = Convert.ToString(sb);

            return Json(returnValue);
        }
        /// <summary>
        /// 设置节点
        /// </summary>
        /// <param name="sb"></param>
        /// <param name="cinerarium"></param>
        private void SetCinerariumEntity(StringBuilder sb, Cinerarium cinerarium)
        {
            sb.Append("<li>");
            sb.Append("<img src='../../Images/danmu.gif' />");
            sb.Append("<br />");
            sb.Append(cinerarium.Hao);
            sb.Append("<br />");
            sb.Append("<input type='checkbox' name='Cinerarium" + cinerarium.Pai + "' value='" + cinerarium.RowGuid +
                      "' /></li>");
        }
        private void SetSelectAllPai(StringBuilder sb,int? paino,string painame)
        {
            sb.Append("<li>" + painame + "：<br /><input type='checkbox' name='Cinerarium" + paino + "' id='Cinerarium" + paino + "' /></li>");
        }
        /// <summary>
        /// 设置div结尾
        /// </summary>
        /// <param name="sb"></param>
        private void SetEnd(StringBuilder sb)
        {
            sb.Append("</ul>");
        }
        /// <summary>
        /// 设置div的开头
        /// </summary>
        /// <param name="sb"></param>
        private void SetStart(StringBuilder sb)
        {
            sb.Append("<ul>");
        }
        public JsonResult GetPai(string areaguid)
        {

            var pai = new SysEntities().Cinerarium.Where(s => s.AreaGuid == areaguid).GroupBy(g => new { g.Pai, g.PaiName }).Select(p => p.Key);

            return Json(pai);

        }

        public JsonResult EditPai(FormCollection collection, string painame, int paisort, string areaguid)
        {
            string returnValue = string.Empty;
            string[] editId = collection["query"].GetString().Split(',');
            if (editId != null && editId.Length > 0)
            {
                List<Cinerarium> cemeteries = new List<Cinerarium>();
                CinerariumBLL CinerariumBll = new CinerariumBLL();
                foreach (var editid in editId)
                {
                    if (!string.IsNullOrEmpty(editid))
                    {
                        Cinerarium Cinerarium = db.Cinerarium.SingleOrDefault(s => s.RowGuid == editid);
                        Cinerarium.PaiName = painame;
                        Cinerarium.Pai = paisort;
 
                        db.Detach(Cinerarium);
                        cemeteries.Add(Cinerarium);

                    }
                }
                if (m_BLL.EditCollection(ref validationErrors, cemeteries.AsQueryable()))
                {
                    LogClassModels.WriteServiceLog(Suggestion.UpdateSucceed + "，信息的Id为" + string.Join(",", editId), "消息"
                        );//删除成功，写入日志
                    return Json("OK");
                }
                else
                {
                    if (validationErrors != null && validationErrors.Count > 0)
                    {
                        validationErrors.All(a =>
                        {
                            returnValue += a.ErrorMessage;
                            return true;
                        });
                    }
                    LogClassModels.WriteServiceLog(Suggestion.UpdateFail + "，信息的Id为" + string.Join(",", editId) + "," + returnValue, "消息"
                        );//删除失败，写入日志
                }
            }
            return Json(returnValue);
        }

        public JsonResult EditHao(FormCollection collection, int edithao)
        {
            string returnValue = string.Empty;
            string[] editId = collection["query"].GetString().Split(',');
            if (editId != null && editId.Length > 0)
            {
                List<Cinerarium> cemeteries = new List<Cinerarium>();

                foreach (var editid in editId)
                {
                    if (!string.IsNullOrEmpty(editid))
                    {
                        Cinerarium Cinerarium = db.Cinerarium.SingleOrDefault(s => s.RowGuid == editid);
                        Cinerarium.Hao = edithao;

                        db.Detach(Cinerarium);
                        cemeteries.Add(Cinerarium);

                    }
                }
                if (m_BLL.EditCollection(ref validationErrors, cemeteries.AsQueryable()))
                {
                    LogClassModels.WriteServiceLog(Suggestion.UpdateSucceed + "，信息的Id为" + string.Join(",", editId), "消息"
                        );//删除成功，写入日志
                    return Json("OK");
                }
                else
                {
                    if (validationErrors != null && validationErrors.Count > 0)
                    {
                        validationErrors.All(a =>
                        {
                            returnValue += a.ErrorMessage;
                            return true;
                        });
                    }
                    LogClassModels.WriteServiceLog(Suggestion.UpdateFail + "，信息的Id为" + string.Join(",", editId) + "," + returnValue, "消息"
                        );//删除失败，写入日志
                }
            }
            return Json(returnValue);
        }

        public JsonResult AjaxDingJia(FormCollection collection, decimal price)
        {
            string returnValue = string.Empty;
            string[] editId = collection["query"].GetString().Split(',');
            if (editId != null && editId.Length > 0)
            {
                List<Cinerarium> cemeteries = new List<Cinerarium>();

                foreach (var editid in editId)
                {
                    if (!string.IsNullOrEmpty(editid))
                    {
                        Cinerarium Cinerarium = db.Cinerarium.SingleOrDefault(s => s.RowGuid == editid);
                        Cinerarium.Price = price;

                        db.Detach(Cinerarium);
                        cemeteries.Add(Cinerarium);

                    }
                }
                if (m_BLL.EditCollection(ref validationErrors, cemeteries.AsQueryable()))
                {
                    LogClassModels.WriteServiceLog(Suggestion.UpdateSucceed + "，信息的Id为" + string.Join(",", editId), "消息"
                        );//删除成功，写入日志
                    return Json("OK");
                }
                else
                {
                    if (validationErrors != null && validationErrors.Count > 0)
                    {
                        validationErrors.All(a =>
                        {
                            returnValue += a.ErrorMessage;
                            return true;
                        });
                    }
                    LogClassModels.WriteServiceLog(Suggestion.UpdateFail + "，信息的Id为" + string.Join(",", editId) + "," + returnValue, "消息"
                        );//删除失败，写入日志
                }
            }
            return Json(returnValue);
        }

        public string GetFullName(string rowguid)
        {
            string ret = string.Empty;
            Cinerarium cin=new Cinerarium();
            cin = new CinerariumBLL().GetById(rowguid);
            CinerariumArea area = new SysEntities().CinerariumArea.SingleOrDefault(s => s.RowGuid == cin.AreaGuid);
            ret = area.Name + "第" + cin.Pai + "排" + "第"+cin.Hao+"号";
            return ret;
        }
    }
}


